﻿namespace Blaze.Framework.LuaExtensions
{
    using System;
    using UnityEngine;
    using XLua;

    /// <summary>
    /// 为lua中的Framework/Events/UnityEvent提供事件信息。
    /// </summary>
    public class UnityEventHelper : MonoBehaviour
    {
        /// <summary>
        /// 初始化。
        /// </summary>
        /// <param name="table">Framework/Events/UnityEvent.lua</param>
        public void Initialize(LuaTable table)
        {
            mUpdate = table.Get<Action<float, float>>("Update");
            mLateUpdate = table.Get<Action>("LateUpdate");
            mFixedUpdate = table.Get<Action<float>>("FixedUpdate");
            mOnApplicationFocus = table.Get<Action<bool>>("OnApplicationFocus");
            mOnApplicationPause = table.Get<Action<bool>>("OnApplicationPause");
            mOnApplicationQuit = table.Get<Action>("OnApplicationQuit");
        }

        private void cleanup()
        {
            mFixedUpdate = null;
            mLateUpdate = null;
            mOnApplicationFocus = null;
            mOnApplicationPause = null;
            mOnApplicationQuit = null;
            mUpdate = null;
        }

        private void FixedUpdate()
        {
            mFixedUpdate(Time.fixedDeltaTime);
        }

        private void LateUpdate()
        {
            mLateUpdate();
        }

        private void OnApplicationFocus(bool hasFocus)
        {
            mOnApplicationFocus(hasFocus);
        }

        private void OnApplicationPause(bool isPause)
        {
            mOnApplicationPause(isPause);
        }

        private void OnApplicationQuit()
        {
            mOnApplicationQuit();
        }

        private void OnDestroy()
        {
            cleanup();
        }

        private void Update()
        {
            mUpdate(Time.deltaTime, Time.unscaledDeltaTime);
        }

        private Action<float> mFixedUpdate;
        private Action mLateUpdate;
        private Action<bool> mOnApplicationFocus;
        private Action<bool> mOnApplicationPause;
        private Action mOnApplicationQuit;
        private Action<float, float> mUpdate;
    }
}